package git.soulbgm.util;

import git.soulbgm.bean.BeanDefinition;
import git.soulbgm.imitate.Bean1;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-22 14:38
 * @description
 */
public class BeanUtil {

    /**
     * 通过cglib
     *
     * @param clz           class类型
     * @param argumentTypes 构造函数的参数数据类型
     * @param arguments     构造函数的参数值
     * @param <T>           泛型
     * @return 实例化对象
     */
    public static <T> T instanceByCglib(Class<T> clz, Class[] argumentTypes, Object[] arguments) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clz);
        enhancer.setCallback(NoOp.INSTANCE);
        if (argumentTypes != null) {
            return (T) enhancer.create(argumentTypes, arguments);
        } else {
            return (T) enhancer.create();
        }
    }

    /**
     * 通过cglib
     *
     * @param clz class类型
     * @param <T> 泛型
     * @return 实例化对象
     */
    public static <T> T instanceByCglib(Class<T> clz) {
        return instanceByCglib(clz, null, null);
    }

    /**
     * 通过cglib
     *
     * @param className class类型
     * @param <T>       泛型
     * @return 实例化对象
     */
    public static <T> T instanceByCglib(String className) {
        try {
            Class<T> clz = (Class<T>) Class.forName(className);
            return instanceByCglib(clz, null, null);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        int in = 1;
        String str = "1";
        double dou = 1D;
        byte by = 1;
        float flo = 1F;
        boolean boo = true;
        long lon = 1L;
        char ch = 1;
        Bean1 bean1 = instanceByCglib(Bean1.class, new Class[]{
                int.class, String.class, double.class, byte.class, float.class, boolean.class, long.class, char.class
        }, new Object[]{
                in, str, dou, by, flo, boo, lon, ch
        });
        System.out.println(bean1);
    }

}
